/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RRHH_controlador;

import CONTABILIDAD_MODELO.CON_CENTRO_COSTO;
import CONTABILIDAD_MODELO.CON_COMPROBANTE;
import CONTABILIDAD_MODELO.CON_CUENTA_COMPROBANTE;
import CONTABILIDAD_MODELO.CON_CUENTA_CONTABLE;
import CONTABILIDAD_MODELO.CON_PARAMETRIZACION_LINEAS_CO;
import Conexion.Conexion;
import RRHH_Modelo.RHH_LINEAS_CORPORATIVAS;
import RRHH_Modelo.RHH_PLANILLA_CORPORATIVOS;
import RRHH_Modelo.RHH_PLAN_CORP_COMPROBANTE;
import RRHH_Modelo.RHH_USUARIO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author equipo_4
 */
@MultipartConfig
@WebServlet(name = "RRHH_PLANILLA_LINEAS_CORP_CONTROLLER", urlPatterns = {"/RRHH_PLANILLA_LINEAS_CORP_CONTROLLER"})
public class RRHH_PLANILLA_LINEAS_CORP_CONTROLLER extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RRHH_PLANILLA_CELULARES_CONTROLLER</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RRHH_PLANILLA_CELULARES_CONTROLLER at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String evento = request.getParameter("evento");
            String html="";
            RHH_USUARIO usuario = ((RHH_USUARIO)request.getSession().getAttribute("usr"));
            Conexion con = new Conexion(usuario.getPASSWORD(), usuario.getPASSWORD());            

            switch(evento)
            {
                case "llenartabla":
                    html=llenartabla(request,con);
                    break;
                case "pagar":
                    html=pagar(request,con);
                    break;
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            response.getWriter().write(html);
        } catch (SQLException ex) {
            Logger.getLogger(RRHH_PLANILLA_LINEAS_CORP_CONTROLLER.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(RRHH_PLANILLA_LINEAS_CORP_CONTROLLER.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
    

    private String llenartabla(HttpServletRequest request, Conexion con) throws SQLException {
        int ano = Integer.parseInt(request.getParameter("ano"));
        int mes = Integer.parseInt(request.getParameter("mes"));
        
        String html="<input type='hidden' name='evento' value='pagar'/><input type='hidden' name='ano' value='"+ano+"'/><input type='hidden' name='mes' value='"+mes+"'/><ul>";
        List<RHH_LINEAS_CORPORATIVAS> lista = new RHH_LINEAS_CORPORATIVAS(con).Todos("");
        for(RHH_LINEAS_CORPORATIVAS lineas:lista)
        {
            RHH_PLANILLA_CORPORATIVOS plan=new RHH_PLANILLA_CORPORATIVOS(con).ExisteXanoYmes(ano, mes, lineas.getID());
            if(plan!=null)
                html+="<li><span>"+lineas.getNUMERO()+"</span><input type='number' value='"+plan.getMONTO_FACTURADO()+"' step='0.5' min='0' name='linea_"+lineas.getID()+"'/></li>";
            else
                html+="<li><span>"+lineas.getNUMERO()+"</span><input type='number' value='0.0' step='0.5' min='0' name='linea_"+lineas.getID()+"'/></li>";
        }
        return html+"</ul>";
    }

    private void eliminacionPlanilla(int ano, int mes, Conexion con) throws SQLException
    {
        try
        {
            List<RHH_PLANILLA_CORPORATIVOS> pc = new RHH_PLANILLA_CORPORATIVOS(con).TodosXanoYmes(ano, mes);        
            
            String idcc = "";

            for(RHH_PLANILLA_CORPORATIVOS list:pc)
            {
                RHH_PLAN_CORP_COMPROBANTE aux =new RHH_PLAN_CORP_COMPROBANTE(con).buscarIdCC(list.getID());
                idcc+=aux.getID_CUENTA_COMPROBANTE()+",";
                aux.EliminarXid();
            }
            if(pc.size()>0)
            {
                idcc=idcc.substring(0,idcc.length()-1);        
                CON_CUENTA_COMPROBANTE cc = new CON_CUENTA_COMPROBANTE();
                cc.setCon(con);
                cc.EliminarMultiplesId(idcc);
            }
            new RHH_PLANILLA_CORPORATIVOS(con).elimiar(ano,mes);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }

    private String pagar(HttpServletRequest request, Conexion con) throws SQLException, Exception {
        int ano = Integer.parseInt(request.getParameter("ano"));
        int mes = Integer.parseInt(request.getParameter("mes"));   
        eliminacionPlanilla(ano, mes, con);
        List<RHH_LINEAS_CORPORATIVAS> lineas = new RHH_LINEAS_CORPORATIVAS(con).Todos("");
        CON_COMPROBANTE comprobante = new CON_COMPROBANTE();
        comprobante.setCon(con);
        comprobante=comprobante.BuscarXRECURRENTE(7);
        
        for(RHH_LINEAS_CORPORATIVAS linea:lineas)
        {
            Double monto = Double.parseDouble(request.getParameter("linea_"+linea.getID()));
            RHH_PLANILLA_CORPORATIVOS plan = new RHH_PLANILLA_CORPORATIVOS(con);
            plan.setANO(ano);
            plan.setMES(mes);
            plan.setID_CORPORATIVOS(linea.getID());
            plan.setID_SUCURSAL(linea.getID_SUCURSAL());
            plan.setMONTO_FACTURADO(monto);
            int idplan=plan.Insertar();
            CON_PARAMETRIZACION_LINEAS_CO param = new CON_PARAMETRIZACION_LINEAS_CO(con).BuscarXlinea(linea.getID());
            int idcc = -1;
            if(param.getID_CENTRO_COSTO()>0)
            {
                CON_CENTRO_COSTO centro = new CON_CENTRO_COSTO(con).BuscarXid(param.getID_CENTRO_COSTO());                
                CON_CUENTA_COMPROBANTE cc = new CON_CUENTA_COMPROBANTE(0.0, 0.0, 0.0, 0.0, monto, "Pago linea Corporativa "+mes+"/"+ano, param.getID_CUENTA(), comprobante.getID(),param.getID_CENTRO_COSTO(), centro.getDESCRIPCION(), 0.0);
                cc.setCon(con);
                idcc=cc.Insertar();
            }
            else
            {
                CON_CUENTA_CONTABLE cuenta = new CON_CUENTA_CONTABLE(con);
                cuenta=cuenta.BuscarXid(param.getID_CUENTA());                
                CON_CUENTA_COMPROBANTE cc = new CON_CUENTA_COMPROBANTE(0.0, 0.0, 0.0, 0.0, monto, "Pago linea Corporativa "+mes+"/"+ano, param.getID_CUENTA(), comprobante.getID(),0.0, cuenta.getDESCRIPCION(), 0.0);
                cc.setCon(con);
                idcc=cc.Insertar();
            }
            if(idcc!=-1)
            {
                RHH_PLAN_CORP_COMPROBANTE pcc = new RHH_PLAN_CORP_COMPROBANTE(idplan,idcc);
                pcc.setCon(con);
                pcc.Insertar();
            }
        }
         new RHH_PLANILLA_CORPORATIVOS(con).pagar(ano, mes);
        return true+"";
    }
}
